<template>
  <AdVxeModal
    v-bind="$attrs"
    @register="register"
    :id="formIndex"
    :title="`${t('iot.route.device.config.title')} - ${FormModeEntityRef.Display}`"
    :help-message="`${t('common.form')}：${formIndex}`"
    :cancel-text="t('common.cancelText')"
    :close-func="handleClose"
    :ok-text="FormModeEntityRef.OkBtnTitle"
    @ok="handleOk"
    @open-change="handleOpenChange"
    width="50%"
  >
    <BasicForm @register="registerForm" @contextmenu="handleContextMenu">
      <template #configValue="{ model, field }">
        <template v-if="model.ValidValues && Object.keys(model.ValidValues).length > 0">
          <Select
            v-model:value="model[field]"
            :dropdown-match-select-width="false"
            :show-search="true"
            :allow-clear="true"
            option-filter-prop="label"
            :placeholder="t('iot.route.device.config.valueText')"
            style="width: 100%; min-width: 100%"
          >
            <SelectOption v-for="(value, key) in model.ValidValues" :key="key" :value="key" :label="value">
              {{ value }}
            </SelectOption>
          </Select>
        </template>
        <template v-else>
          <Input v-model:value="model[field]" :placeholder="t('iot.route.device.config.valueText')" />
        </template>
      </template>
      <template #configValidValues="{ model, field }">
        <CodeEditor
          :value="JSON.stringify(model[field])"
          :mode="MODE.JSON"
          :line-numbers="true"
          @change="handleValidValuesChange"
        />
      </template>
    </BasicForm>
  </AdVxeModal>

  <PrintTemplateModal @register="templateModalRegister" v-bind="templateModalProps" />
</template>
<script lang="ts" setup>
  import type { DeviceConfigInputDto, DeviceConfigOutputDto } from '@/api/iot/admin/device/model';
  import type { FormSchema } from '@/components/Form';

  import type { PropType } from 'vue';

  import type { AjaxResult } from '#/request';

  import { ref } from 'vue';

  import { isFunction } from '@eacloud/utils';

  import { createDeviceConfig, deleteDeviceConfig, readDeviceNodes, updateDeviceConfig } from '@/api/iot/admin/device';
  import { PrintTemplateModal, useAdPrint } from '@/components/AdPrint';
  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import { CodeEditor, MODE } from '@/components/CodeMirrorEditor';
  import { destroyContextMenu } from '@/components/ContextMenu';
  import { BasicForm, useForm } from '@/components/Form';
  import { FormModeEntity, FormModeEnum } from '@/enums/formEnum';
  import { useContextMenu } from '@/hooks/web/useContextMenu';
  import { useI18n } from '@/hooks/web/useI18n';
  import { Input, Select } from 'ant-design-vue';

  defineOptions({ name: 'DeviceConfigModal' });

  const props = defineProps({
    /** 关闭回调，返回true关闭窗体 */
    closeFunc: {
      type: Function as PropType<(formMode: FormModeEnum, record?: DeviceConfigOutputDto) => Promise<boolean>>,
      default: null,
    },
    /** 提交前回调，返回false不执行内置提交逻辑，返回true执行内置提交逻辑 */
    beforeSubmitFunc: {
      type: Function as PropType<(formMode: FormModeEnum, record?: DeviceConfigOutputDto) => Promise<boolean>>,
      default: null,
    },
    /** 提交后回调，返回true关闭窗体 */
    afterSubmitFunc: {
      type: Function as PropType<
        (formMode: FormModeEnum, result?: AjaxResult | null, record?: DeviceConfigOutputDto) => Promise<boolean>
      >,
      default: null,
    },
  });

  const SelectOption = Select.Option;

  const { t } = useI18n();
  const { createContextMenu } = useContextMenu();
  const formIndex = 'iot_deviceconfig_detail';
  const keyField = 'Id';

  const formModeRef = ref<FormModeEnum>(FormModeEnum.Ok);
  const FormModeEntityRef = ref<FormModeEntity>(new FormModeEntity(formModeRef.value));

  const schemas: FormSchema[] = [
    {
      field: 'Id',
      helpMessage: `${t('common.field')}：${'Id'}`,
      component: 'Input',
      label: t('entity.idTitle'),
      componentProps: { disabled: true },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'DeviceId',
      helpMessage: `${t('common.field')}：${'DeviceId'}`,
      component: 'ApiSelect',
      label: t('iot.route.device.title'),
      required: true,
      componentProps: {
        api: readDeviceNodes,
        // use name as label
        labelField: 'Name',
        // use id as value
        valueField: 'Id',
        showSearch: true,
        optionFilterProp: 'Name',
        // not request untill to select
        immediate: true,
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'DeviceName',
      helpMessage: `${t('common.field')}：${'DeviceName'}`,
      component: 'Input',
      label: t('iot.route.device.nameText'),
      ifShow: false,
    },
    {
      field: 'Name',
      helpMessage: `${t('common.field')}：${'Name'}`,
      component: 'Input',
      label: t('iot.route.device.config.nameText'),
      required: true,
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Value',
      helpMessage: `${t('common.field')}：${'Value'}`,
      // component: 'Input',
      label: t('iot.route.device.config.valueText'),
      slot: 'configValue',
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Description',
      helpMessage: `${t('common.field')}：${'Description'}`,
      component: 'Input',
      label: t('iot.route.device.config.descriptionText'),
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'OrderNumber',
      helpMessage: `${t('common.field')}：${'OrderNumber'}`,
      component: 'InputNumber',
      label: t('iot.route.device.config.orderNumberText'),
      componentProps: {
        style: { width: '100%' },
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'Remark',
      helpMessage: `${t('common.field')}：${'Remark'}`,
      component: 'InputTextArea',
      label: t('iot.route.device.group.remarkText'),
      componentProps: {
        showCount: true,
      },
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    { field: 'divider-basic', component: 'Divider', label: '', colProps: { span: 24 } },
    {
      field: 'ValidValues',
      helpMessage: `${t('common.field')}：${'ValidValues'}`,
      // component: 'Input',
      label: t('iot.route.device.config.validValuesText'),
      slot: 'configValidValues',
      colProps: {
        // span: 24,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 24, // ≥1200px
        xxl: 24, // ≥1600px
        // xxxl: 24, // ≥2000px 3.0
      },
    },
    { field: 'divider-basic', component: 'Divider', label: '', colProps: { span: 24 } },
    {
      field: 'CreatedTime',
      helpMessage: `${t('common.field')}：${'CreatedTime'}`,
      component: 'DatePicker',
      label: t('entity.creationAudited.createdTimeTitle'),
      componentProps: {
        disabled: true,
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
    {
      field: 'UpdatedTime',
      helpMessage: `${t('common.field')}：${'UpdatedTime'}`,
      component: 'DatePicker',
      label: t('entity.updateAudited.updatedTimeTitle'),
      componentProps: {
        disabled: true,
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        style: { width: '100%' },
      },
      colProps: {
        // span: 12,
        xs: 24, // <576px
        sm: 24, // ≥576px
        md: 24, // ≥768px
        lg: 24, // ≥992px
        xl: 12, // ≥1200px
        xxl: 12, // ≥1600px
        // xxxl: 12, // ≥2000px 3.0
      },
    },
  ];

  const [registerForm, { resetFields, getFieldsValue, setFieldsValue, validate }] = useForm({
    labelWidth: 150,
    schemas,
    showActionButtonGroup: false,
    compact: true,
  });

  const [register, { setModalProps, closeModal, changeLoading }] = useModalInner(async (data) => {
    changeLoading(true);
    try {
      await clearInputDto();
      const record = (data?.record || {}) as DeviceConfigOutputDto;
      if (data.formMode) {
        formModeRef.value = data.formMode as FormModeEnum;
        FormModeEntityRef.value = new FormModeEntity(formModeRef.value);
      }
      if (record) {
        await setInputDto({
          ...record,
        });
      }
    } finally {
      changeLoading(false);
    }
  });

  // #region "加载状态"
  const loadingRef = ref(false);
  /** 开启加载状态 */
  function openLoading() {
    changeLoading(true);
    setModalProps({ okLoading: true, cancelLoading: true });
    loadingRef.value = true;
  }
  /** 关闭加载状态 */
  function closeLoading() {
    changeLoading(false);
    setModalProps({ okLoading: false, cancelLoading: false });
    loadingRef.value = false;
  }
  // #endregion
  // #region 定义高级打印
  const { printContextMenus, templateModalRegister, templateModalProps } = useAdPrint({
    formIndex,
    keyField,
    getFormData: () => getFieldsValue(),
  });
  /** 处理上下文菜单(右键菜单) */
  function handleContextMenu(e: MouseEvent) {
    const element = document.elementFromPoint(e.clientX, e.clientY) as Element;
    const cursor = document.defaultView?.getComputedStyle(element, null).cursor;
    // console.log('handleContextMenu', {
    //   cursor: cursor,
    // });

    let items: any[] = [];
    switch (FormModeEntityRef.value.FormMode) {
      case FormModeEnum.Ok:
      case FormModeEnum.Edit:
      case FormModeEnum.ReadOnly:
        if (!cursor || cursor === 'default' || cursor === 'auto') {
          items = [...printContextMenus];
        }
        break;
    }
    if (items && items?.length > 0) {
      createContextMenu({
        event: e,
        styles: {
          border: '1px solid #eee',
          'border-radius': '2px',
          'box-shadow': '3px 3px 3px rgb(0 0 0 / 15%)',
        },
        items: [...items],
      });
    }
  }
  // #endregion

  /** 获取输入DTO */
  function getInputDto(): DeviceConfigInputDto {
    const record = getFieldsValue() as DeviceConfigInputDto;
    return record;
  }
  /** 设置输入DTO */
  async function setInputDto(values: any) {
    let inputDto = getInputDto();
    inputDto = { ...inputDto, ...values };
    await setFieldsValue({ ...inputDto });
  }
  /** 清除输入DTO */
  async function clearInputDto() {
    await resetFields();
  }

  /** 获取输出DTO */
  function getOutputDto(): DeviceConfigOutputDto {
    const record = getFieldsValue() as DeviceConfigOutputDto;
    return record;
  }

  /** 处理关闭按钮 */
  async function handleClose() {
    openLoading();

    const { closeFunc } = props;
    try {
      if (closeFunc && isFunction(closeFunc)) {
        const outputDto = getOutputDto();
        const result = await closeFunc(FormModeEntityRef.value.FormMode, outputDto);
        return result;
      }
    } finally {
      closeLoading();
    }
    return true;
  }
  /** 处理确定按钮 */
  async function handleOk() {
    const data = await validate();
    if (!data) return;
    // console.log(data);

    openLoading();
    const { beforeSubmitFunc, afterSubmitFunc } = props;
    try {
      const inputDto = getInputDto();
      const outputDto = getOutputDto();
      // console.log('handleOk', inputDto);
      let innerSubmit = true;
      let innerCloseModal = true;
      if (beforeSubmitFunc && isFunction(beforeSubmitFunc)) {
        innerSubmit = await beforeSubmitFunc(FormModeEntityRef.value.FormMode, outputDto);
      }
      let result: AjaxResult | null = null;
      if (innerSubmit) {
        switch (FormModeEntityRef.value.FormMode) {
          case FormModeEnum.Add:
            result = await createDeviceConfig([inputDto]);
            break;
          case FormModeEnum.Edit:
            result = await updateDeviceConfig([inputDto]);
            break;
          case FormModeEnum.Delete:
            result = await deleteDeviceConfig([inputDto.Id]);
            break;
        }
      }
      if (afterSubmitFunc && isFunction(afterSubmitFunc)) {
        innerCloseModal = await afterSubmitFunc(FormModeEntityRef.value.FormMode, result, outputDto);
      }
      if (innerCloseModal) {
        closeModal();
      }
    } finally {
      closeLoading();
    }
  }

  /** 打开或者关闭触发 */
  function handleOpenChange(open: boolean) {
    if (!open) {
      destroyContextMenu();
    }
  }

  /** 设置有效值变更 */
  async function handleValidValuesChange(value: any) {
    let validValues: any = {};
    try {
      if (value) {
        validValues = JSON.parse(value);
      }
      await setInputDto({
        ValidValues: validValues,
      });
    } catch {
      validValues = {};
    }
  }
</script>
<style lang="scss" scoped></style>
